package com.whcoding.test.common.file;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-05-25 14:11
 **/
public class ImgUtils {
	/**
	 * 图片转base64
	 *
	 * @param filePath 图片文件路径
	 * @return
	 */
	public static String toBase64String(String filePath) {
		if (null == filePath || 0 == filePath.length()) {
			throw new RuntimeException("图片路径不能为空！！");
		}
		InputStream in = null;
		byte[] data = null;
		try {
			//读取图片字节数组
			in = new FileInputStream(filePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		StringBuilder sb = new StringBuilder();
		sb.append("data:image/jpg;base64,");
		sb.append(Base64.getEncoder().encodeToString(data));

		//对字节数组Base64编码，返回Base64编码过的字节数组字符串
		return sb.toString();
	}

	public static void main(String[] args) {
		System.out.println(toBase64String("D:\\下载\\desktop.png"));
	}
}
